package com.demo.base.webIoLog;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description 记录请求和返回日志
 * @date 2023/3/13 5:17 PM
 */
@Configuration
@Slf4j
public class WebLogConfig {

    @Bean
    public OncePerRequestFilter contentCachingRequestFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(
                    final HttpServletRequest request,
                    final HttpServletResponse response,
                    final FilterChain filterChain)
                    throws ServletException, IOException {

                ContentCachingRequestWrapper wrappedRequest =
                        new ContentCachingRequestWrapper(request);
                ContentCachingResponseWrapper wrappedResponse =
                        new ContentCachingResponseWrapper(response);
                filterChain.doFilter(wrappedRequest, wrappedResponse);

                log.info("http request: {}", new String(wrappedRequest.getContentAsByteArray()));
                log.info("http response: {}", new String(wrappedResponse.getContentAsByteArray()));

                wrappedResponse.copyBodyToResponse();
            }
        };
    }
}
